package com.uenpay.im.ui.old.activity.dynamic;

import android.os.AsyncTask;

import com.qiyunxin.android.http.utils.StreamUtility;
import com.uenpay.im.configuration.APIConfiguration;

import org.apache.http.HttpStatus;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class UploadDynamicBg {

	private IUploadFileListener _onUploadFileListener;

	public UploadDynamicBg(byte[] fileData,
			IUploadFileListener onUploadFileListener) {
		_onUploadFileListener = onUploadFileListener;
		new FileUploadTask(fileData).execute();
	}

	private class FileUploadTask extends
			AsyncTask<Object, Integer, FileMessage> {
		byte[] toUploadData;

		public FileUploadTask(byte[] fileData) {
			toUploadData = fileData;
		}

		@Override
		protected FileMessage doInBackground(Object... params) {
			FileMessage fileMessage = new FileMessage();
			String end = "\r\n";
			String boundary = "multipart/form-data; boundary=--------------------------7d03135102b8";
			try {

				String pattern = "type=setFriendDynamicBgPic&method=eliteall.friend";

				URL url = new URL(APIConfiguration.getBaseUrl() + pattern);
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				con.setDoInput(true);
				con.setDoOutput(true);
				con.setUseCaches(false);
				con.setRequestMethod("POST");
				con.setRequestProperty("Content-Type", boundary);
				DataOutputStream ds = new DataOutputStream(
						con.getOutputStream());
				ds.writeBytes("----------------------------7d03135102b8" + end);
				ds.writeBytes("Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"abc.jpg\""
						+ end);
				ds.writeBytes("Content-Type: application/octet-stream" + end);
				ds.writeBytes(end);
				ds.write(toUploadData);
				ds.writeBytes(end);
				ds.writeBytes("----------------------------7d03135102b8--"
						+ end);
				ds.flush();
				int statusCode = con.getResponseCode();

				if (statusCode == HttpStatus.SC_OK) {
					String result = StreamUtility.readStream(con
							.getInputStream());
					JSONObject json = new JSONObject(result);

					fileMessage.status = json.optInt("status");
					fileMessage.msg = json.optString("msg");
					fileMessage.fileid = json.optString("fileid");
					fileMessage.filehash = json.optString("filehash");
				} else {
					StringBuilder sb = new StringBuilder();
					sb.append("Upload image failed. ");
					sb.append("The http response status code is ");
					sb.append(statusCode);
					sb.append(". The request url is ");
					sb.append(url);
					// Logger.error("HttpInvokeEngine", sb.toString());
				}

			} catch (Exception e) {
				// Logger.error("UploadFileInvokeItem", "JSONException", e);
			}
			return fileMessage;
		}

		@Override
		protected void onPostExecute(FileMessage result) {
			_onUploadFileListener.OnUploadFile(result);
		}
	}
}
